package mysql

import (
	"context"
	"gorm.io/gorm"
	"time"
)

type Order struct {
	gorm.Model
	OrderSn    string
	Userid     int64
	Goodsid    int64
	Goodsname  string
	TotalPrice float64
	PayTime    time.Time
	Status     int8
}

type OrderProduct struct {
	gorm.Model
	OrderId    int64
	Userid     int64
	Order      Order `gorm:"ForeignKey:OrderId"`
	Goodsid    int64
	Goodsname  string
	Goodsprice float64
	Count      int64
	Status     int8
}

func CreateOrder(order Order) Order {
	db.Create(&order)
	return order
}

func CreateOrderProduct(orderProduct OrderProduct) OrderProduct {
	db.Create(&orderProduct)
	return orderProduct
}

func GetPrice(userid string) (map[string]float64, map[string]string, map[string]int) {
	m := map[string]int{}
	re, _ := st.LRange(context.Background(), "userid "+userid, 0, -1).Result()
	for _, s := range re {
		m[s]++
	}
	n := []int{}
	strs := []string{}
	for s, i := range m {
		n = append(n, i)
		strs = append(strs, s)
	}
	//sum := float64(0)
	rs := map[string]float64{}
	names := map[string]string{}
	for i, _ := range strs {
		p := Product{}
		db.Where("id", strs[i]).Find(&p)
		rs[strs[i]] = p.GoodsPrice * float64(n[i])
		names[strs[i]] = p.GoodsName
	}
	return rs, names, m
}

func CompleteOrder(orderid int) string {
	o := Order{}
	r := OrderProduct{}
	db.Where("id", orderid).Find(&o)
	db.Where("orderid", orderid).Find(&r)
	if o.ID == 0 || r.ID == 0 {
		return "0"
	}
	o.Status = 1
	r.Status = 1
	db.Where("id", orderid).Save(&o)
	db.Where("orderid", orderid).Save(&r)
	return "1"
}

func GetOrder(orderid string) Order {
	o := Order{}
	db.Where("id", orderid).Find(&o)
	return o
}
